# -*- coding: utf-8 -*-
import sys
from pyquery import PyQuery as pq
sys.path.append('..')
from base.spider import Spider


class Spider(Spider):
    def __init__(self):
        self.headers = {
            'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7',
            'accept-language': 'zh-CN,zh;q=0.9,en;q=0.8',
            'sec-ch-ua': '"Not/A)Brand";v="8", "Chromium";v="134", "Google Chrome";v="134"',
            'sec-ch-ua-platform': '"macOS"',
            'sec-fetch-dest': 'document',
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.8 Mobile/15E148 Safari/604.1'
        }
        self.host = "https://4k-av.com"
        super().__init__()

    def init(self, extend=""):
        """初始化方法"""
        pass

    def getName(self):
        """返回爬虫名称"""
        return "4KAV爬虫"

    def isVideoFormat(self, url):
        """检查URL是否为视频格式"""
        video_formats = ['.mp4', '.m3u8', '.flv', '.avi', '.mov', '.mkv']
        return any(fmt in url for fmt in video_formats)

    def manualVideoCheck(self):
        """是否需要手动检查视频"""
        return False

    def destroy(self):
        """清理资源"""
        pass

    def homeContent(self, filter):
        """首页内容"""
        data = self.getpq()
        result = {}
        
        # 获取分类
        classes = []
        for item in list(data('#category ul li').items())[:-1]:
            classes.append({
                'type_name': item.text(),
                'type_id': item('a').attr('href')
            })
        
        result['class'] = classes
        result['list'] = self.getlist(data('#MainContent_scrollul ul li'), '.poster span')
        return result

    def homeVideoContent(self):
        """首页视频内容"""
        return []

    def categoryContent(self, tid, pg, filter, extend):
        """分类内容"""
        data = self.getpq(f"{tid}page-{pg}.html")
        result = {}
        result['list'] = self.getlist(data('#MainContent_newestlist .virow .NTMitem'))
        result['page'] = pg
        result['pagecount'] = 9999
        result['limit'] = 90
        result['total'] = 999999
        return result

    def detailContent(self, ids):
        """详情内容"""
        data = self.getpq(ids[0])
        v = data('#videoinfo')
        
        # 提取视频信息
        vod = {
            'vod_name': data('#tophead h1').text().split(' ')[0],
            'type_name': v('#MainContent_tags.tags a').text(),
            'vod_year': v('#MainContent_videodetail.videodetail a').text(),
            'vod_remarks': v('#MainContent_titleh12 h2').text(),
            'vod_content': v('p.cnline').text(),
            'vod_play_from': '4KAV',
            'vod_play_url': ''
        }
        
        # 处理播放列表
        vlist = data('#rtlist li')
        jn = f"{vod['vod_name']}_" if 'EP0' in vlist.eq(0)('span').text() else ''
        
        if vlist:
            episodes = []
            for i, item in enumerate(list(vlist.items())):
                if i == 0:
                    episodes.append(f"{jn}{item('span').text()}${ids[0]}")
                else:
                    episodes.append(f"{jn}{item('span').text()}${item('a').attr('href')}")
            
            vod['vod_play_url'] = '#'.join(episodes)
        else:
            vod['vod_play_url'] = f"{vod['vod_name']}${ids[0]}"
        
        return {'list': [vod]}

    def searchContent(self, key, quick, pg="1"):
        """搜索内容"""
        data = self.getpq(f"/s?k={key}")
        return {'list': self.getlist(data('#MainContent_newestlist .virow.search .NTMitem.Main'))}

    def playerContent(self, flag, id, vipFlags):
        """播放内容"""
        try:
            data = self.getpq(id)
            url = data('#MainContent_videowindow source').attr('src')
            
            if not url:
                raise Exception("未找到播放地址")
                
            parse = 0
        except Exception as e:
            parse = 1
            url = f"{self.host}{id}"
            print(f"播放地址获取失败，使用备用方案: {str(e)}")
        
        headers = {
            'origin': self.host,
            'referer': f'{self.host}/',
            'sec-ch-ua-platform': '"macOS"',
            'user-agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.8 Mobile/15E148 Safari/604.1',
        }
        
        return {'parse': parse, 'url': url, 'header': headers}

    def localProxy(self, param):
        """本地代理"""
        pass

    def liveContent(self, url):
        """直播内容"""
        pass

    def getlist(self, data, selector='.resyear label[title="分辨率"]'):
        """提取视频列表"""
        videos = []
        for item in data.items():
            title_parts = item('.title h2').text().split(' ')
            
            videos.append({
                'vod_id': item('.title a').attr('href'),
                'vod_name': title_parts[0],
                'vod_pic': item('.poster img').attr('src'),
                'vod_remarks': title_parts[-1] if len(title_parts) > 1 else '',
                'vod_year': item(selector).text()
            })
        return videos

    def getpq(self, path=''):
        """获取PyQuery对象"""
        url = f"{self.host}{path}"
        try:
            response = self.fetch(url, headers=self.headers)
            data = response.text
            return pq(data)
        except Exception as e:
            print(f"获取页面失败: {str(e)}")
            # 尝试使用UTF-8编码处理
            try:
                return pq(data.encode('utf-8'))
            except:
                return pq('<html></html>')  # 返回空文档避免后续错误